package role

import (
	"encoding/json"
	"sanguo/node/common/asynwrap"
	"sanguo/node/common/db"
	"strconv"
	"sanguo/node/node_game"
	"github.com/go-redis/redis"
)

func (this *Role) saveBase(callback func(error)) {
	jsonStr, err := json.Marshal(this.data)
	if nil != err {
		node_game.Errorln(this.user.GetUserID(),"basedata Marshal error:",err)
		this.dirty = false
		if nil != callback {
			callback(nil)
		}
		return
	}
	this.dirty = false
	key := "role:" + this.user.GetUserID()
	asynwrap.Wrap(db.GetRedisClient("game").HSet)(func(ret []interface{}) {
		_, err := ret[0].(*redis.BoolCmd).Result()

		if nil != err {
			this.dirty = true
			//log
		}

		if nil != callback {
			callback(err)
		}

	}, key, strconv.FormatUint(this.GetID(), 10), jsonStr)
}

func (this *Role) saveModule(callback func(error)) {

	if len(this.module) == 0 {
		if nil != callback {
			callback(nil)
		}
		return
	}

	fields := map[string]interface{}{}
	key := "roleModuleData:" + strconv.FormatUint(this.GetID(), 10)
	s := []saveAble{}
	for _, v := range this.module {
		if v.IsDirty() {
			s = append(s, v)
			v.PackJson(fields)
			v.ClearDirtyFlag()
		}
	}

	if len(fields) > 0 {
		asynwrap.Wrap(db.GetRedisClient("game").HMSet)(func(ret []interface{}) {
			_, err := ret[0].(*redis.StatusCmd).Result()
			if nil != err {
				//log
				for _, v := range s {
					v.SetDirtyFlag()
				}
			}
			if nil != callback {
				callback(err)
			}
		}, key, fields)
	} else {
		callback(nil)
	}
}

func (this *Role) Save(callback func(error)) {
	if this.dirty {
		this.saveBase(func(err error) {
			if nil != err {
				if nil != callback {
					callback(err)
				}
			} else {
				this.saveModule(callback)
			}
		})
	} else {
		this.saveModule(callback)
	}
}
